import secrets
import string
import json

def generate_password(length=12):
    # 定义密码字符集：大小写字母、数字和特殊符号
    characters = string.ascii_letters + string.digits + string.punctuation
    # 从字符集中随机选择字符，生成指定长度的密码
    password = ''.join(secrets.choice(characters) for _ in range(length))
    return password

class Contest:
    def __init__(self):
        self.chessRight = 1
        self.winner = 0
        self.chessKey = generate_password()
        self.boardData = {
            "0": { "status": 0, "css": 'block', "timer": 0},
            "1": { "status": 0, "css": 'block', "timer": 0},
            "2": { "status": 0, "css": 'block', "timer": 0},

            "3": { "status": 0, "css": 'block', "timer": 0},
            "4": { "status": 0, "css": 'block', "timer": 0},
            "5": { "status": 0, "css": 'block', "timer": 0},

            "6": { "status": 0, "css": 'block', "timer": 0},
            "7": { "status": 0, "css": 'block', "timer": 0},
            "8": { "status": 0, "css": 'block', "timer": 0},
        }
        self.step = 0
        self.seatsA = -1
        self.seatsB = -1
        self.gameStatus = False

    def init(self):
        self.chessRight = 1
        self.winner = 0
        self.chessKey = generate_password()
        self.boardData = {
            "0": { "status": 0, "css": 'block', "timer": 0},
            "1": { "status": 0, "css": 'block', "timer": 0},
            "2": { "status": 0, "css": 'block', "timer": 0},

            "3": { "status": 0, "css": 'block', "timer": 0},
            "4": { "status": 0, "css": 'block', "timer": 0},
            "5": { "status": 0, "css": 'block', "timer": 0},

            "6": { "status": 0, "css": 'block', "timer": 0},
            "7": { "status": 0, "css": 'block', "timer": 0},
            "8": { "status": 0, "css": 'block', "timer": 0},
        }
        self.step = 0
        self.seatsA = -1
        self.seatsB = -1
        self.gameStatus = False

    # 分配座位
    def sit_down(self, pos, id):
        if pos == 1 and self.seatsA == 0:
            self.seatsA = id
            self.check_game_status()
            return True
        elif pos == 2 and self.seatsB == 0:
            self.seatsB = id
            self.check_game_status()
            return True
        else:
            return False
        
    # putchess
    def put_chess(self, chessdata):
        self.boardData = json.loads(chessdata)
        self.step += 1
        self.chessRight = 2 if self.chessRight == 1 else 1

        for key in self.boardData.keys():
            if self.boardData[key]['timer'] > 0:
                self.boardData[key]['timer'] -= 1
                
            if self.boardData[key]['timer'] == 0:
                self.boardData[key]['status'] = 0

            if self.boardData[key]['status'] == 0:
                self.boardData[key]['css'] = 'block'
            elif self.boardData[key]['status'] == 1:
                self.boardData[key]['css'] = 'block blocktick'
            elif self.boardData[key]['status'] == 2:
                self.boardData[key]['css'] = 'block blockcross'
            if self.boardData[key]['timer'] == 1:
                self.boardData[key]['css'] += ' weak'
        
        self.winner = self.check_winner()
        if self.winner != 0:
            self.gameStatus = False

    def check_game_status(self):
        if self.seatsA != -1 and self.seatsB != -1:
            self.gameStatus = True
            return True
        else:
            self.gameStatus = False
            return False
        
    def check_winner(self):
        """
        判断井字棋当前是否有玩家胜利
        :param board_data: 棋盘数据字典（格式如示例中的self.boardData）
        :return: 胜利玩家的status（1或2），未分胜负返回0
        """
        # 定义所有可能的胜利组合（行、列、对角线）
        win_patterns = [
            ["0", "1", "2"],  # 第一行
            ["3", "4", "5"],  # 第二行
            ["6", "7", "8"],  # 第三行
            ["0", "3", "6"],  # 第一列
            ["1", "4", "7"],  # 第二列
            ["2", "5", "8"],  # 第三列
            ["0", "4", "8"],  # 主对角线
            ["2", "4", "6"]   # 副对角线
        ]
        
        for pattern in win_patterns:
            # 获取当前组合三个位置的status值
            statuses = [self.boardData[pos]["status"] for pos in pattern]
            # 检查是否三个位置status相同且不为0
            if len(set(statuses)) == 1 and statuses[0] != 0:
                return statuses[0]
        
        # 没有找到胜利组合
        return 0
